package com.stone.serverless.core.classloader.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import lombok.SneakyThrows;

import java.io.*;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * @Description: TODO
 * @Author: MECHREVO
 * @Date: 2022/1/18 11:17
 * @Version: 1.0.0
 */
public class JarFileUtil {

    private static File tempFolder = new File(System.getProperty("java.io.tmpdir"));

    //需要的 jar 包解压到文件夹
    public static File unpackToFolder(JarFile jarFile, String componentName, String version) {
        File folder = FileUtil.file(tempFolder, componentName + "-" + version);
        FileUtil.mkdir(folder);
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry jarEntry = entries.nextElement();
            String name = jarEntry.getName();
            if (name.endsWith(".jar")) {
                name = name.replace("lib/", "");
                name = name.replace("lib\\", "");
                File cf = new File(folder, name);
                unpack(jarFile, jarEntry, cf);
            }
        }
        return folder;
    }

    public static void delete(String componentName, String version) {
        File folder = new File(tempFolder, componentName + "-" + version);
        try {
            FileUtil.del(folder);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    // 解压 jar 包;
    private static void unpack(JarFile jarFile, JarEntry entry, File file) {
        InputStream inputStream = null;
        try {
            inputStream = jarFile.getInputStream(entry);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            IoUtil.copy(inputStream, fileOutputStream);
            IoUtil.close(fileOutputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        IoUtil.close(inputStream);
    }

    @SneakyThrows
    public static File getFile(String fileName, String componentName, String version) {
        fileName = fileName.replace("lib/", "");
        fileName = fileName.replace("lib\\", "");
        File folder = new File(tempFolder, componentName + "-" + version);
        File file = FileUtil.file(folder, fileName);
        return file;
    }
}
